package com.commander.spring.cloud.route;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

/**
 * description:
 * <p>
 * Date: 2020-06-11
 * <p>
 * Time: 17:51
 *
 * @author zhangxin
 */
@Component
public class NacosDynamicRouteServiceImpl implements ApplicationEventPublisherAwareService {
	
	@Autowired
	private RouteDefinitionWriter writer;
	private ApplicationEventPublisher publisher;
	
	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher publisher) {
		this.publisher = publisher;
	}
	
	@Override
	public void add(RouteDefinition definition) {
		writer.save(Mono.just(definition)).subscribe();
		this.publisher.publishEvent(new RefreshRoutesEvent(this));
	}
	
	@Override
	public void delete(String id) {
		this.writer.delete(Mono.just(id));
	}
	
	@Override
	public void update(RouteDefinition definition) {
		writer.delete(Mono.just(definition.getId()));
		writer.save(Mono.just(definition)).subscribe();
		this.publisher.publishEvent(new RefreshRoutesEvent(this));
	}
	
	@Override
	public void refreshRoutes() {
		publisher.publishEvent(new RefreshRoutesEvent(this));
	}

}
